<?php
namespace app\wechat\controller;

use Jssdk\JSSDK;
use think\Controller;
use think\Db;

class Xydzp extends Controller
{
    private $obj;
    public function _initialize()
    {
        parent::_initialize();
        $this->obj = model('Xydzp');
    }

    public function index()
    {
        if ($_SERVER['HTTP_HOST'] != 'localhost:8078') {
            if (input('param.oauth') != 'yes') {
                if (!isset($_SERVER['HTTP_REFERER']) || $_SERVER['HTTP_REFERER'] != 'http://www.hnjyxh.com/index/activity/zjjz_advert') {
                    $this->error('参数错误!');
                }
            }

            if (!session('?openid')) {
                $base_url = request()->module() . '/' . request()->controller() . '/' . request()->action();
                session('base_url', $base_url);
                session('base_param', input('param.'));

                session('model', 'wechat');
                $this->redirect('index/member/index', ['base_model' => 'wechat']);
                //\app\index\controller\Common::oauth(); // 发起授权
            }
        } else {
            session('old_id_list', null);
        }

        // 可抽奖次数
//        $this->assign('num', input('param.count', 0));

        // 抽奖对应的欢迎语数据
        $ids = input('param.ids');
        $ids = explode('-', $ids);

//        if (input('param.count', 0) != count($ids)) {
//            $this->error('抽奖次数异常');
//        }

        $id_list = [];
        $old_id_list = session('old_id_list');
        //dump($old_id_list);
        foreach ($ids as $v) {
            if (!isset($old_id_list[$v]) || $old_id_list[$v] == 0) {
                $id_list[$v] = 0;
            }
        }
        session('id_list', $id_list);
        //dump($id_list);

        $this->assign('num', count($id_list));

        // 获取大转盘
        $id = input('param.id');
        $data = $this->obj->get(['id' => $id]);
        $this->assign('data', $data);

        // 获取转盘活动
        $prize = model('xydzp_prize')->all(['xydzp_id' => $id]);
        $this->assign('prize', $prize);

        // 获取转盘中奖记录
        $xydzp_prize_record = model('xydzp_prize_record')->where(['xydzp_id' => $id])->order('id desc')->select();
        $this->assign('xydzp_prize_record', $xydzp_prize_record);

        // 我的中奖记录
        $my_prize_record = model('xydzp_prize_record')->all(['xydzp_id' => $id, 'openid' => session('openid')]);
        $this->assign('my_prize_record', $my_prize_record);

        // 获取收货地址
        $address = model('xydzp_address')->get(['xydzp_id' => $id, 'openid' => session('openid')]);
        $this->assign('address', $address);
        return view();
    }

    public function get_prize() {
        try {
            if (!session('?openid')) {
                throw new \Exception('用户信息拉取失败');
            }

            $id = input('param.id');
            $prize = model('xydzp_prize')->all(['xydzp_id' => $id]);

            $prize_array = [];
            $probability = 1000; // 几率基数为1000
            foreach ($prize as $k => $v) {
                //$count = model('xydzp_prize_record')->where(['xydzp_id' => $id, 'xydzp_prize_id' => $v->id])->count();
                if (!$v->num) {
                    unset($prize[$k]);
                    continue;
                }
                for($i = 0; $i < $v->probability; $i++) {
                    $prize_array[] = $k + 1;
                }
                $probability -= $v->probability;
            }
            for($i = 0; $i < $probability; $i++) {
                $prize_array[] = $k + 2;
            }
            $prize_key = array_rand($prize_array);
            $prize_id = $prize_array[$prize_key] == $k + 2 ? 0 : $prize[$k]->id;

            // 通知修改记录状态
            $old_id_list = session('old_id_list');
            $id_list = session('id_list');
            foreach ($id_list as $k => $v) {
                if ($v == 0) {
                    break;
                }
            }
//            file_get_contents('http://www.hnjyxh.com/index/activity/edit_draw/id/' . $k);
            get_data('http://www.hnjyxh.com/index/activity/edit_draw/id/' . $k);
            $id_list[$k] = 1;
            $old_id_list[$k] = 11;
            session('old_id_list', $old_id_list);

            return json(['code' => 200, 'prize' => $prize_array[$prize_key], 'prize_id' => $prize_id]);
        } catch ( \Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }
    }

    public function save_prize_record() {
        Db::startTrans();
        try {
            if (!session('?openid')) {
                throw new \Exception('用户信息拉取失败');
            }

            $data = [
                'xydzp_id' => input('param.id'),
                'xydzp_prize_id' => input('param.prize_id'),
                'openid' => session('openid'),
                'nickname' => session('nickname')
            ];
            model('xydzp_prize_record')->save($data);

            model('xydzp_prize')->where(['id' => input('param.prize_id')])->setDec('num');

            $prize =  model('xydzp_prize')->where(['id' => input('param.prize_id')])->find();

            Db::commit();
            return json(['code' => 200, 'nickname' => session('nickname'), 'prize_name' => $prize->name, 'time' => date('Y-m-d H:i')]);
        } catch ( \Exception $e) {
            Db::rollback();
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }
    }

    public function save_address() {
        Db::startTrans();
        try {
            if (!session('?openid')) {
                throw new \Exception('用户信息拉取失败');
            }

            $data = [
                'xydzp_id' => input('param.xydzp_id'),
                'openid' => session('openid'),
                'address' => input('param.address'),
                'link_man' => input('param.link_man'),
                'mobile' => input('param.mobile'),
            ];

            $address = model('xydzp_address')->get(['xydzp_id' => input('param.xydzp_id'), 'openid' => session('openid')]);
            if ($address) {
                model('xydzp_address')->save($data, ['id' => $address->id]);
            } else {
                model('xydzp_address')->save($data);
            }

            Db::commit();
            return json(['code' => 200]);
        } catch ( \Exception $e) {
            Db::rollback();
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }
    }
}
